#!/usr/bin/env python3
"""
订阅支付流程演示脚本
演示完整的订阅支付流程：创建支付会话 -> 支付成功 -> 创建订阅
"""

import sys
import os
import json
from datetime import datetime

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from services.subscription_service import SubscriptionService
from services.customer_service import CustomerService
from services.product_service import ProductService
from services.webhook_service import WebhookService
from models.subscription_models import SubscriptionCheckoutRequest
from utils.config import Config


def demo_subscription_payment_flow():
    """演示订阅支付流程"""
    print("🚀 订阅支付流程演示")
    print("=" * 80)
    
    # 创建服务实例
    customer_service = CustomerService()
    product_service = ProductService()
    subscription_service = SubscriptionService()
    webhook_service = WebhookService(
        customer_service=customer_service,
        product_service=product_service,
        subscription_service=subscription_service
    )
    
    print("📝 初始状态:")
    print(f"  - 客户数量: {len(customer_service.customers)}")
    print(f"  - 产品数量: {len(product_service.products)}")
    print(f"  - 订阅数量: {len(subscription_service.subscriptions)}")
    
    # 步骤1: 创建订阅支付会话
    print("\n🔍 步骤1: 创建订阅支付会话")
    print("-" * 50)
    
    # 获取第一个产品
    products = list(product_service.products.values())
    
    if not products:
        print("❌ 没有可用的产品")
        return
    
    product = products[0]
    
    # 创建一个新的客户用于演示
    import uuid
    new_customer_data = {
        'id': f"customer_demo_{int(datetime.now().timestamp())}",
        'name': 'Demo Customer',
        'email': f'demo_{int(datetime.now().timestamp())}@example.com',
        'stripe_customer_id': f'cus_demo_{int(datetime.now().timestamp())}',
        'created_at': datetime.now().isoformat(),
        'updated_at': datetime.now().isoformat()
    }
    
    # 将新客户添加到客户服务中
    customer_service.customers[new_customer_data['id']] = new_customer_data
    from utils.data_store import DataStore
    DataStore.save_data(Config.CUSTOMERS_FILE, customer_service.customers)
    
    customer = new_customer_data
    
    print(f"  📋 使用客户: {customer['name']} ({customer['email']})")
    print(f"  📋 使用产品: {product['name']}")
    
    # 创建支付会话请求
    checkout_request = SubscriptionCheckoutRequest(
        customer_id=customer['id'],
        product_id=product['id'],
        success_url="http://localhost:8003/subscription/success?session_id={CHECKOUT_SESSION_ID}",
        cancel_url="http://localhost:8003/subscription/cancel"
    )
    
    try:
        # 模拟支付会话创建（跳过实际的Stripe API调用）
        checkout_result = {
            'session_id': f'cs_demo_{int(datetime.now().timestamp())}',
            'checkout_url': 'https://checkout.stripe.com/pay/cs_demo_123',
            'customer_id': customer['id'],
            'product_id': product['id']
        }
        print("  ✅ 支付会话创建成功（模拟）")
        print(f"  📋 会话ID: {checkout_result['session_id']}")
        print(f"  📋 支付URL: {checkout_result['checkout_url']}")
        
        # 步骤2: 模拟支付成功后的webhook事件
        print("\n🔍 步骤2: 模拟支付成功后的webhook事件")
        print("-" * 50)
        
        # 模拟Stripe订阅创建事件
        stripe_subscription = {
            "id": f"sub_demo_{int(datetime.now().timestamp())}",
            "customer": customer['stripe_customer_id'],
            "status": "active",
            "current_period_start": int(datetime.now().timestamp()),
            "current_period_end": int(datetime.now().timestamp()) + 86400 * 30,
            "cancel_at_period_end": False,
            "metadata": {
                "local_customer_id": customer['id'],
                "local_product_id": product['id'],
                "session_id": checkout_result['session_id']
            },
            "items": {
                "data": [
                    {
                        "id": f"si_demo_{int(datetime.now().timestamp())}",
                        "price": {
                            "id": product['stripe_price_id'],
                            "product": product['stripe_product_id']
                        },
                        "quantity": 1
                    }
                ]
            }
        }
        
        print(f"  📝 模拟订阅创建事件: {stripe_subscription['id']}")
        print(f"  📝 客户: {customer['name']}")
        print(f"  📝 产品: {product['name']}")
        print(f"  📝 状态: {stripe_subscription['status']}")
        
        # 记录更新前的订阅数量
        initial_count = len(subscription_service.subscriptions)
        print(f"  📊 更新前订阅数量: {initial_count}")
        
        # 处理订阅创建事件
        webhook_result = webhook_service.subscription_created(stripe_subscription)
        print("  ✅ 订阅创建事件处理成功")
        print(f"  📋 Webhook结果: {webhook_result}")
        
        # 步骤3: 验证订阅创建结果
        print("\n🔍 步骤3: 验证订阅创建结果")
        print("-" * 50)
        
        # 重新加载数据
        subscription_service.reload_data()
        final_count = len(subscription_service.subscriptions)
        print(f"  📊 更新后订阅数量: {final_count}")
        
        if final_count > initial_count:
            print("  ✅ 订阅数量已增加，新订阅创建成功")
            
            # 查找新创建的订阅
            new_subscription = None
            for sub_id, sub_data in subscription_service.subscriptions.items():
                if sub_data.get('stripe_subscription_id') == stripe_subscription['id']:
                    new_subscription = sub_data
                    break
            
            if new_subscription:
                print("  📋 新订阅详情:")
                print(f"    - 本地ID: {new_subscription['id']}")
                print(f"    - Stripe ID: {new_subscription['stripe_subscription_id']}")
                print(f"    - 客户ID: {new_subscription['customer_id']}")
                print(f"    - 产品ID: {new_subscription['product_id']}")
                print(f"    - 状态: {new_subscription['status']}")
                print(f"    - 创建时间: {new_subscription['created_at']}")
                print(f"    - 更新时间: {new_subscription['updated_at']}")
                
                # 验证客户和产品信息
                customer_info = customer_service.get_customer(new_subscription['customer_id'])
                product_info = product_service.get_product(new_subscription['product_id'])
                
                if customer_info:
                    print(f"    - 客户信息: {customer_info['name']} ({customer_info['email']})")
                if product_info:
                    print(f"    - 产品信息: {product_info['name']} - {product_info['description']}")
            else:
                print("  ❌ 未找到新创建的订阅记录")
        else:
            print("  ⚠️  订阅数量未增加")
        
        # 步骤4: 模拟订阅支付成功事件
        print("\n🔍 步骤4: 模拟订阅支付成功事件")
        print("-" * 50)
        
        # 更新订阅状态为支付成功
        stripe_subscription['status'] = 'active'
        stripe_subscription['latest_invoice'] = f"in_demo_{int(datetime.now().timestamp())}"
        
        payment_result = webhook_service.subscription_payment_succeeded(stripe_subscription)
        print("  ✅ 订阅支付成功事件处理成功")
        print(f"  📋 支付结果: {payment_result}")
        
        # 最终验证
        subscription_service.reload_data()
        final_subscription = None
        for sub_id, sub_data in subscription_service.subscriptions.items():
            if sub_data.get('stripe_subscription_id') == stripe_subscription['id']:
                final_subscription = sub_data
                break
        
        if final_subscription:
            print("  📋 最终订阅状态:")
            print(f"    - 状态: {final_subscription['status']}")
            print(f"    - 当前周期开始: {final_subscription['current_period_start']}")
            print(f"    - 当前周期结束: {final_subscription['current_period_end']}")
            print(f"    - 取消设置: {final_subscription['cancel_at_period_end']}")
        
    except Exception as e:
        print(f"❌ 演示失败: {e}")
        import traceback
        traceback.print_exc()


def main():
    """主函数"""
    print("🎯 订阅支付流程完整演示")
    print("=" * 80)
    print("📝 演示内容:")
    print("  1. 创建订阅支付会话")
    print("  2. 模拟支付成功后的webhook事件")
    print("  3. 验证订阅创建结果")
    print("  4. 模拟订阅支付成功事件")
    print("  5. 最终状态验证")
    print("=" * 80)
    
    try:
        demo_subscription_payment_flow()
        
        print("\n" + "=" * 80)
        print("🎉 订阅支付流程演示完成！")
        print("\n📝 演示总结:")
        print("  - ✅ 支付会话创建成功")
        print("  - ✅ Webhook事件处理正常")
        print("  - ✅ 本地订阅数据创建成功")
        print("  - ✅ 数据同步机制正常")
        print("  - ✅ 支付成功事件处理正常")
        print("\n💡 实际使用流程:")
        print("  1. 用户点击订阅支付按钮")
        print("  2. 系统创建Stripe支付会话")
        print("  3. 用户完成支付")
        print("  4. Stripe发送webhook事件")
        print("  5. 系统自动创建本地订阅记录")
        print("  6. 页面显示新的订阅项目")
        
    except Exception as e:
        print(f"\n❌ 演示失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
